package indi.mozping.helper;

import org.springframework.beans.factory.annotation.Autowired;

import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author by mozping
 * @Classname LockTestController
 * @Description TODO
 * @Date 2019/11/13 16:16
 */
public class LockTest {

    public static CountDownLatch latch = new CountDownLatch(1);
    private static int count = 0;
    private static final String KEY = "key";

    private AtomicInteger fail = new AtomicInteger();
    private static ThreadLocal<String> lockValue = new ThreadLocal<String>();

    @Autowired
    DistributeLock redisDistributeLock;

    public String test() throws InterruptedException {
        for (int i = 0; i < 500; i++) {
            Thread t = new Thread(new MyRunnable(), "name" + i);
            t.start();
        }
        Thread.sleep(1500);
        latch.countDown();
        Thread.sleep(10000);
        System.out.println("失败：" + fail);
        return "ok";
    }

    public class MyRunnable implements Runnable {

        public void run() {
            try {
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            String name = Thread.currentThread().getName();
            String s = UUID.randomUUID().toString();
            if (redisDistributeLock.tryLock(KEY, s)) {
                lockValue.set(s);
                try {
                    ++count;
                    System.out.println("--------线程 " + name + " 得到锁，执行计算后是：" + count);
                } finally {
                    redisDistributeLock.unLock(KEY, lockValue.get());
                    lockValue.remove();
                }
            } else {
                fail.getAndIncrement();
                System.out.println("--------线程获取锁失败 ");
            }
        }
    }
}